
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import urllib


#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")

    lis = soup.select(".zpp ul li")


    for li in lis:
        tempData = resultData()

        try:
            tempData["titleName"] = li.select(".zpp_h a")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = li.select(".zpp_h a")[0]["href"]
        except:
            pass
        try:
            tempData["author"] = [li.select(".zpp_s")[0].text.strip()]
        except:
            pass
        try:
            tempData["source"] = li.select(".zpp_s")[1].text.strip()
        except:
            pass
        allData.append(tempData)

    return allData

def getData(keyword):

    headers = {
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'https://brill.com/',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('sw', keyword),
        ('field',0),
        ('cpage','')
    )
    proxies = {
        "http": "http://qf:qf3.1415@202.112.118.7:10086/"
    }
    response = requests.post('http://www.dachengdata.com/asearch/search', headers=headers, params=params,proxies=proxies)

    allData = formData(response)

    return allData


def index(request):


    # page = 1
    data = json.loads(request.POST.get('data', '1'))

    allData= getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")